package com.drg.center.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.drg.center.entity.param.SysDictListDTO;
import com.drg.center.mapper.SysDictMapper;
import com.guaike.core.entity.context.ContextHolder;
import com.guaike.core.mybatis.plugins.BaseDAO;
import com.drg.center.entity.SysDictItemPO;
import com.drg.center.entity.SysDictPO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author: zhangxilin
 * @Date: 2023/10/25
 */
@Repository
public class SysDictDAO extends BaseDAO<SysDictMapper, SysDictPO> {

    @Autowired
    private SysDictItemDAO sysDictItemDAO;

    public IPage<SysDictPO> findPage(SysDictListDTO param){
        LambdaQueryWrapper<SysDictPO> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(param.getKeyword())){
            queryWrapper.eq(SysDictPO::getDictCode,param.getKeyword());
            queryWrapper.or(qw-> qw.like(SysDictPO::getDictName,param.getKeyword()));
        }
        queryWrapper.orderByDesc(SysDictPO::getCreateTime);
        return getBaseMapper().selectPage(new Page<>(param.getPageIndex(), param.getPageSize()), queryWrapper);
    }

    public boolean isExistCode(String dictCode){
        LambdaQueryWrapper<SysDictPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictPO::getDictCode,dictCode);
        return getBaseMapper().selectCount(queryWrapper)>0? true:false;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(SysDictPO record){
        updateById(record);

        LambdaUpdateWrapper<SysDictItemPO> itemPOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        itemPOLambdaUpdateWrapper.set(SysDictItemPO::getStatus, record.getStatus());
        itemPOLambdaUpdateWrapper.set(SysDictItemPO::getUpdateUser, ContextHolder.getUserId());
        itemPOLambdaUpdateWrapper.set(SysDictItemPO::getUpdateTime, new Date());
        itemPOLambdaUpdateWrapper.eq(SysDictItemPO::getDictCode,record.getDictCode());
        sysDictItemDAO.update(itemPOLambdaUpdateWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(SysDictPO record){
        del(record.getId());
        sysDictItemDAO.del(SysDictItemPO::getDictCode,record.getDictCode());
    }
}
